const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { query } = require('../config/db');

/**
 * 管理员登录控制器
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function login(req, res) {
  try {
    const { username, password } = req.body;

    // 基本验证：检查用户名和密码是否为空
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    // 验证用户名和密码长度
    if (username.trim().length < 3) {
      return res.status(400).json({
        success: false,
        message: '用户名长度至少3个字符'
      });
    }

    if (password.length < 6) {
      return res.status(400).json({
        success: false,
        message: '密码长度至少6个字符'
      });
    }

    // 根据用户名查询管理员记录
    const adminQuery = `
      SELECT id, username, password_hash, is_super_admin, is_active, created_at 
      FROM admins 
      WHERE username = ?
    `;
    
    const adminResult = await query(adminQuery, [username.trim()]);

    // 检查用户是否存在
    if (adminResult.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    const admin = adminResult[0];

    // 检查用户是否被禁用
    if (!admin.is_active) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 使用bcryptjs比较密码
    const isPasswordValid = await bcrypt.compare(password, admin.password_hash);

    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 生成JWT Token
    const tokenPayload = {
      id: admin.id,
      username: admin.username,
      is_super_admin: admin.is_super_admin,
      type: 'admin'
    };

    const token = jwt.sign(
      tokenPayload,
      process.env.JWT_SECRET,
      { 
        expiresIn: '1d', // 1天过期
        issuer: 'parking-system', // 签发者
        audience: 'admin' // 受众
      }
    );

    // 准备返回的用户信息（不包含密码）
    const userInfo = {
      id: admin.id,
      username: admin.username,
      is_super_admin: admin.is_super_admin,
      is_active: admin.is_active,
      created_at: admin.created_at
    };

    // 记录登录日志（可选）
    console.log(`管理员登录成功: ${admin.username} (ID: ${admin.id}) - ${new Date().toLocaleString()}`);

    // 返回成功响应
    res.status(200).json({
      success: true,
      message: '登录成功',
      data: {
        token,
        userInfo
      }
    });

  } catch (error) {
    console.error('管理员登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误，请稍后重试'
    });
  }
}

/**
 * 获取当前登录管理员信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getCurrentAdmin(req, res) {
  try {
    // 从中间件中获取用户信息（需要先实现JWT验证中间件）
    const adminId = req.admin.id;

    const adminQuery = `
      SELECT id, username, is_super_admin, is_active, created_at 
      FROM admins 
      WHERE id = ? AND is_active = 1
    `;
    
    const adminResult = await query(adminQuery, [adminId]);

    if (adminResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: '管理员不存在或已被禁用'
      });
    }

    res.status(200).json({
      success: true,
      data: adminResult[0]
    });

  } catch (error) {
    console.error('获取管理员信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车场列表（支持分页和搜索）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLots(req, res) {
  try {
    const { page = 1, pageSize = 10, name = '', status = '' } = req.query;

    // 参数验证
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);

    if (pageNum < 1 || pageSizeNum < 1 || pageSizeNum > 100) {
      return res.status(400).json({
        success: false,
        message: '分页参数无效'
      });
    }

    // 构建查询条件
    let whereConditions = [];
    let queryParams = [];

    if (name.trim()) {
      whereConditions.push('p.name LIKE ?');
      queryParams.push(`%${name.trim()}%`);
    }

    if (status.trim()) {
      whereConditions.push('p.status = ?');
      queryParams.push(status.trim());
    }

    const whereClause = whereConditions.length > 0
      ? `WHERE ${whereConditions.join(' AND ')}`
      : '';

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM parking_lots p
      ${whereClause}
    `;

    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const offset = (pageNum - 1) * pageSizeNum;
    const listQuery = `
      SELECT
        p.id,
        p.name,
        p.category_id,
        c.name as category_name,
        p.address,
        p.total_spaces,
        p.monthly_sales,
        p.rating,
        p.airport_distance_km,
        p.station_distance_km,
        p.shuttle_time_minutes,
        p.contact_phone,
        p.backup_phone,
        p.status,
        p.created_at,
        p.updated_at
      FROM parking_lots p
      LEFT JOIN parking_lot_categories c ON p.category_id = c.id
      ${whereClause}
      ORDER BY p.created_at DESC
      LIMIT ${pageSizeNum} OFFSET ${offset}
    `;

    const listResult = await query(listQuery, queryParams);

    res.status(200).json({
      success: true,
      data: {
        list: listResult,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    });

  } catch (error) {
    console.error('获取停车场列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取单个停车场详细信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLotById(req, res) {
  try {
    const { id } = req.params;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    const parkingLotQuery = `
      SELECT
        p.*,
        c.name as category_name
      FROM parking_lots p
      LEFT JOIN parking_lot_categories c ON p.category_id = c.id
      WHERE p.id = ?
    `;

    const result = await query(parkingLotQuery, [id]);

    if (result.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    res.status(200).json({
      success: true,
      data: result[0]
    });

  } catch (error) {
    console.error('获取停车场详情错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 创建新停车场
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function createParkingLot(req, res) {
  try {
    const {
      name,
      category_id,
      address,
      total_spaces,
      monthly_sales,
      rating,
      airport_distance_km,
      station_distance_km,
      shuttle_time_minutes,
      contact_phone,
      backup_phone,
      business_documents,
      price_rules,
      service_facilities,
      description,
      image_urls
    } = req.body;

    // 基本验证
    if (!name || !address) {
      return res.status(400).json({
        success: false,
        message: '停车场名称、地址为必填项'
      });
    }

    // 验证车位数
    const spaces = parseInt(total_spaces) || 0;
    if (spaces < 0) {
      return res.status(400).json({
        success: false,
        message: '车位数不能为负数'
      });
    }

    // 验证新字段
    const monthlySalesNum = parseInt(monthly_sales) || 0;
    const ratingNum = parseFloat(rating) || 0.00;
    const airportDistanceNum = airport_distance_km ? parseFloat(airport_distance_km) : null;
    const stationDistanceNum = station_distance_km ? parseFloat(station_distance_km) : null;
    const shuttleTimeNum = shuttle_time_minutes ? parseInt(shuttle_time_minutes) : null;

    // 验证评分范围
    if (ratingNum < 0 || ratingNum > 5) {
      return res.status(400).json({
        success: false,
        message: '评分必须在0-5之间'
      });
    }

    // 验证距离和时间
    if (airportDistanceNum !== null && airportDistanceNum < 0) {
      return res.status(400).json({
        success: false,
        message: '距机场距离不能为负数'
      });
    }

    if (stationDistanceNum !== null && stationDistanceNum < 0) {
      return res.status(400).json({
        success: false,
        message: '距高铁站距离不能为负数'
      });
    }

    if (shuttleTimeNum !== null && shuttleTimeNum < 0) {
      return res.status(400).json({
        success: false,
        message: '摆渡车时间不能为负数'
      });
    }

    const insertQuery = `
      INSERT INTO parking_lots (
        name, category_id, address, total_spaces,
        monthly_sales, rating, airport_distance_km, station_distance_km, shuttle_time_minutes,
        contact_phone, backup_phone, business_documents,
        price_rules, service_facilities, description, image_urls, status
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending_review')
    `;

    const insertParams = [
      name.trim(),
      category_id || null,
      address.trim(),
      spaces,
      monthlySalesNum,
      ratingNum,
      airportDistanceNum,
      stationDistanceNum,
      shuttleTimeNum,
      contact_phone || '',
      backup_phone || '',
      JSON.stringify(business_documents || {}),
      JSON.stringify(price_rules || {}),
      JSON.stringify(service_facilities || []),
      description || '',
      JSON.stringify(image_urls || [])
    ];

    const result = await query(insertQuery, insertParams);

    res.status(201).json({
      success: true,
      message: '停车场创建成功',
      data: {
        id: result.insertId,
        name: name.trim(),
        status: 'pending_review'
      }
    });

  } catch (error) {
    console.error('创建停车场错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 更新停车场信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateParkingLot(req, res) {
  try {
    const { id } = req.params;
    const updateData = req.body;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    // 检查停车场是否存在
    const existingLot = await query('SELECT id FROM parking_lots WHERE id = ?', [id]);
    if (existingLot.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    // 构建更新字段
    const allowedFields = [
      'name', 'category_id', 'address', 'total_spaces',
      'monthly_sales', 'rating', 'airport_distance_km', 'station_distance_km', 'shuttle_time_minutes',
      'contact_phone', 'backup_phone', 'business_documents',
      'price_rules', 'service_facilities', 'description', 'image_urls', 'status'
    ];

    const updateFields = [];
    const updateParams = [];

    for (const field of allowedFields) {
      if (updateData.hasOwnProperty(field)) {
        updateFields.push(`${field} = ?`);

        // 特殊处理JSON字段
        if (['price_rules', 'service_facilities', 'image_urls', 'business_documents'].includes(field)) {
          updateParams.push(JSON.stringify(updateData[field] || (field === 'image_urls' ? [] : {})));
        } else if (field === 'total_spaces') {
          const spaces = parseInt(updateData[field]) || 0;
          if (spaces < 0) {
            return res.status(400).json({
              success: false,
              message: '车位数不能为负数'
            });
          }
          updateParams.push(spaces);
        } else if (field === 'monthly_sales') {
          const sales = parseInt(updateData[field]) || 0;
          if (sales < 0) {
            return res.status(400).json({
              success: false,
              message: '月销量不能为负数'
            });
          }
          updateParams.push(sales);
        } else if (field === 'rating') {
          const ratingValue = parseFloat(updateData[field]) || 0.00;
          if (ratingValue < 0 || ratingValue > 5) {
            return res.status(400).json({
              success: false,
              message: '评分必须在0-5之间'
            });
          }
          updateParams.push(ratingValue);
        } else if (['airport_distance_km', 'station_distance_km'].includes(field)) {
          const distance = updateData[field] ? parseFloat(updateData[field]) : null;
          if (distance !== null && distance < 0) {
            return res.status(400).json({
              success: false,
              message: '距离不能为负数'
            });
          }
          updateParams.push(distance);
        } else if (field === 'shuttle_time_minutes') {
          const time = updateData[field] ? parseInt(updateData[field]) : null;
          if (time !== null && time < 0) {
            return res.status(400).json({
              success: false,
              message: '摆渡车时间不能为负数'
            });
          }
          updateParams.push(time);
        } else {
          updateParams.push(updateData[field]);
        }
      }
    }

    if (updateFields.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的字段'
      });
    }

    // 添加更新时间
    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    updateParams.push(id);

    const updateQuery = `
      UPDATE parking_lots
      SET ${updateFields.join(', ')}
      WHERE id = ?
    `;

    await query(updateQuery, updateParams);

    res.status(200).json({
      success: true,
      message: '停车场更新成功'
    });

  } catch (error) {
    console.error('更新停车场错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 删除停车场
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function deleteParkingLot(req, res) {
  try {
    const { id } = req.params;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    // 检查停车场是否存在
    const existingLot = await query('SELECT id, name FROM parking_lots WHERE id = ?', [id]);
    if (existingLot.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    // 检查是否有关联的订单（可选的业务逻辑）
    const orderCount = await query('SELECT COUNT(*) as count FROM orders WHERE parking_lot_id = ?', [id]);
    if (orderCount[0].count > 0) {
      return res.status(400).json({
        success: false,
        message: '该停车场存在关联订单，无法删除'
      });
    }

    // 删除停车场
    await query('DELETE FROM parking_lots WHERE id = ?', [id]);

    res.status(200).json({
      success: true,
      message: '停车场删除成功'
    });

  } catch (error) {
    console.error('删除停车场错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车场评价列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLotReviews(req, res) {
  try {
    const { parking_lot_id } = req.params;
    const { page = 1, pageSize = 10, status = '' } = req.query;

    if (!parking_lot_id || isNaN(parking_lot_id)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    // 参数验证
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);

    if (pageNum < 1 || pageSizeNum < 1 || pageSizeNum > 100) {
      return res.status(400).json({
        success: false,
        message: '分页参数无效'
      });
    }

    // 构建查询条件
    let whereConditions = ['r.parking_lot_id = ?'];
    let queryParams = [parking_lot_id];

    if (status.trim()) {
      whereConditions.push('r.status = ?');
      queryParams.push(status.trim());
    }

    const whereClause = `WHERE ${whereConditions.join(' AND ')}`;

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM reviews r
      ${whereClause}
    `;

    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const offset = (pageNum - 1) * pageSizeNum;
    const listQuery = `
      SELECT
        r.id,
        r.order_id,
        r.user_id,
        r.parking_lot_id,
        r.rating,
        r.comment,
        r.status,
        r.created_at,
        u.nickname as user_nickname,
        u.avatar_url as user_avatar,
        p.name as parking_lot_name,
        o.order_number
      FROM reviews r
      LEFT JOIN users u ON r.user_id = u.id
      LEFT JOIN parking_lots p ON r.parking_lot_id = p.id
      LEFT JOIN orders o ON r.order_id = o.id
      ${whereClause}
      ORDER BY r.created_at DESC
      LIMIT ${pageSizeNum} OFFSET ${offset}
    `;

    const listResult = await query(listQuery, queryParams);

    // 获取每个评价的回复
    for (let review of listResult) {
      const repliesQuery = `
        SELECT
          rr.id,
          rr.content,
          rr.created_at,
          u.nickname as reply_user_nickname
        FROM review_replies rr
        LEFT JOIN users u ON rr.user_id = u.id
        WHERE rr.review_id = ?
        ORDER BY rr.created_at ASC
      `;
      
      const replies = await query(repliesQuery, [review.id]);
      review.replies = replies;
    }

    res.status(200).json({
      success: true,
      data: {
        list: listResult,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    });

  } catch (error) {
    console.error('获取评价列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 更新评价状态（显示/隐藏）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateReviewStatus(req, res) {
  try {
    const { id } = req.params;
    const { status } = req.body;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '评价ID无效'
      });
    }

    if (!['visible', 'hidden'].includes(status)) {
      return res.status(400).json({
        success: false,
        message: '状态值无效'
      });
    }

    // 检查评价是否存在
    const existingReview = await query('SELECT id FROM reviews WHERE id = ?', [id]);
    if (existingReview.length === 0) {
      return res.status(404).json({
        success: false,
        message: '评价不存在'
      });
    }

    // 更新状态
    await query('UPDATE reviews SET status = ? WHERE id = ?', [status, id]);

    res.status(200).json({
      success: true,
      message: '评价状态更新成功'
    });

  } catch (error) {
    console.error('更新评价状态错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 管理员手动添加评论
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function addParkingLotReview(req, res) {
  try {
    const {
      parking_lot_id,
      user_nickname,
      user_avatar,
      rating,
      comment,
      created_at,
      status = 'approved'
    } = req.body;

    // 输入验证
    if (!parking_lot_id || !user_nickname || !rating || !comment) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数：停车场ID、用户昵称、评分、评论内容'
      });
    }

    if (isNaN(parking_lot_id) || parking_lot_id <= 0) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    if (isNaN(rating) || rating < 1 || rating > 5) {
      return res.status(400).json({
        success: false,
        message: '评分必须在1-5之间'
      });
    }

    if (user_nickname.length > 50) {
      return res.status(400).json({
        success: false,
        message: '用户昵称不能超过50字符'
      });
    }

    if (comment.length > 500) {
      return res.status(400).json({
        success: false,
        message: '评论内容不能超过500字符'
      });
    }

    // 检查停车场是否存在
    const parkingLotExists = await query(
      'SELECT id FROM parking_lots WHERE id = ?',
      [parking_lot_id]
    );

    if (parkingLotExists.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    // 创建或获取临时用户记录（用于存储管理员添加的评论）
    let tempUserId;
    const tempUserQuery = `
      SELECT id FROM users WHERE openid = ? AND nickname = ?
    `;

    const tempOpenid = `admin_temp_${user_nickname}_${Date.now()}`;
    const existingTempUser = await query(tempUserQuery, [tempOpenid, user_nickname]);

    if (existingTempUser.length > 0) {
      tempUserId = existingTempUser[0].id;
    } else {
      // 创建临时用户记录
      const createTempUserQuery = `
        INSERT INTO users (openid, nickname, avatar_url, created_at)
        VALUES (?, ?, ?, NOW())
      `;

      const tempUserResult = await query(createTempUserQuery, [
        tempOpenid,
        user_nickname,
        user_avatar || ''
      ]);

      tempUserId = tempUserResult.insertId;
    }

    // 创建一个虚拟订单ID（用于管理员手动添加的评论）
    // 由于数据库约束要求order_id不能为NULL，我们需要创建一个临时订单记录
    const tempOrderQuery = `
      INSERT INTO orders (
        order_number, user_id, parking_lot_id, license_plate,
        planned_start_time, planned_end_time, total_amount,
        final_amount, status, created_at
      ) VALUES (?, ?, ?, ?, NOW(), NOW(), 0, 0, 'completed', NOW())
    `;

    const tempOrderNumber = `ADMIN_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const tempOrderResult = await query(tempOrderQuery, [
      tempOrderNumber,
      tempUserId,
      parking_lot_id,
      'ADMIN000' // 管理员添加的评论使用固定车牌号
    ]);

    const tempOrderId = tempOrderResult.insertId;

    // 插入评论记录
    const insertQuery = `
      INSERT INTO reviews (
        parking_lot_id, user_id, order_id, rating, comment, status, created_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?)
    `;

    // 处理日期时间格式，确保MySQL兼容
    let reviewCreatedAt;
    if (created_at) {
      // 如果提供了created_at，转换为MySQL DATETIME格式
      const date = new Date(created_at);
      reviewCreatedAt = date.toISOString().slice(0, 19).replace('T', ' ');
    } else {
      // 使用当前时间，格式化为MySQL DATETIME格式
      reviewCreatedAt = new Date().toISOString().slice(0, 19).replace('T', ' ');
    }

    // 将status从'approved'转换为数据库支持的'visible'
    const reviewStatus = (status === 'approved' || status === 'visible') ? 'visible' : 'hidden';

    const result = await query(insertQuery, [
      parking_lot_id,
      tempUserId,
      tempOrderId,
      rating,
      comment,
      reviewStatus,
      reviewCreatedAt
    ]);

    res.status(201).json({
      success: true,
      message: '评论添加成功',
      data: {
        id: result.insertId,
        parking_lot_id: parking_lot_id,
        rating: rating,
        comment: comment,
        user_nickname: user_nickname,
        user_avatar: user_avatar,
        created_at: reviewCreatedAt,
        status: status
      }
    });

  } catch (error) {
    console.error('添加评论失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 回复评价
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function replyToReview(req, res) {
  try {
    const { id } = req.params;
    const { content } = req.body;
    const adminId = req.admin.id; // 从JWT中获取管理员ID

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '评价ID无效'
      });
    }

    if (!content || content.trim().length === 0) {
      return res.status(400).json({
        success: false,
        message: '回复内容不能为空'
      });
    }

    if (content.trim().length > 500) {
      return res.status(400).json({
        success: false,
        message: '回复内容不能超过500字符'
      });
    }

    // 检查评价是否存在
    const existingReview = await query('SELECT id FROM reviews WHERE id = ?', [id]);
    if (existingReview.length === 0) {
      return res.status(404).json({
        success: false,
        message: '评价不存在'
      });
    }

    // 插入回复
    const insertQuery = `
      INSERT INTO review_replies (review_id, user_id, content)
      VALUES (?, ?, ?)
    `;

    const result = await query(insertQuery, [id, adminId, content.trim()]);

    res.status(201).json({
      success: true,
      message: '回复成功',
      data: {
        id: result.insertId
      }
    });

  } catch (error) {
    console.error('回复评价错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车场分类列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLotCategories(req, res) {
  try {
    const categoriesQuery = `
      SELECT id, name, icon_url, sort_order, created_at
      FROM parking_lot_categories
      ORDER BY sort_order ASC, created_at ASC
    `;

    const categories = await query(categoriesQuery);

    res.status(200).json({
      success: true,
      data: categories
    });

  } catch (error) {
    console.error('获取停车场分类错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 搜索用户（用于指派员工）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function searchUsers(req, res) {
  try {
    const { keyword = '' } = req.query;

    if (!keyword.trim()) {
      return res.status(400).json({
        success: false,
        message: '搜索关键词不能为空'
      });
    }

    const searchQuery = `
      SELECT id, nickname, phone_number, avatar_url, created_at
      FROM users
      WHERE nickname LIKE ? OR phone_number LIKE ?
      ORDER BY created_at DESC
      LIMIT 20
    `;

    const searchKeyword = `%${keyword.trim()}%`;
    const users = await query(searchQuery, [searchKeyword, searchKeyword]);

    res.status(200).json({
      success: true,
      data: users
    });

  } catch (error) {
    console.error('搜索用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取指定停车场的所有管理员
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLotManagers(req, res) {
  try {
    const { parkingLotId } = req.params;

    if (!parkingLotId || isNaN(parkingLotId)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    // 检查停车场是否存在
    const parkingLotExists = await query('SELECT id FROM parking_lots WHERE id = ?', [parkingLotId]);
    if (parkingLotExists.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    const managersQuery = `
      SELECT
        u.id,
        u.nickname,
        u.phone_number,
        u.email,
        u.avatar_url,
        u.created_at,
        plm.id as manager_relation_id
      FROM parking_lot_managers plm
      JOIN users u ON plm.user_id = u.id
      WHERE plm.parking_lot_id = ?
      ORDER BY plm.id DESC
    `;

    const managers = await query(managersQuery, [parkingLotId]);

    res.status(200).json({
      success: true,
      data: managers
    });

  } catch (error) {
    console.error('获取停车场管理员错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 为指定停车场添加管理员
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function addParkingLotManager(req, res) {
  try {
    const { parkingLotId } = req.params;
    const { userId } = req.body;

    if (!parkingLotId || isNaN(parkingLotId)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    if (!userId || isNaN(userId)) {
      return res.status(400).json({
        success: false,
        message: '用户ID无效'
      });
    }

    // 检查停车场是否存在
    const parkingLotExists = await query('SELECT id FROM parking_lots WHERE id = ?', [parkingLotId]);
    if (parkingLotExists.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    // 检查用户是否存在
    const userExists = await query('SELECT id, nickname FROM users WHERE id = ?', [userId]);
    if (userExists.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 检查是否已经是管理员
    const existingManager = await query(
      'SELECT id FROM parking_lot_managers WHERE parking_lot_id = ? AND user_id = ?',
      [parkingLotId, userId]
    );

    if (existingManager.length > 0) {
      return res.status(400).json({
        success: false,
        message: '该用户已经是此停车场的管理员'
      });
    }

    // 添加管理员关系
    const insertResult = await query(
      'INSERT INTO parking_lot_managers (parking_lot_id, user_id) VALUES (?, ?)',
      [parkingLotId, userId]
    );

    res.status(201).json({
      success: true,
      message: '添加管理员成功',
      data: {
        id: insertResult.insertId,
        parking_lot_id: parkingLotId,
        user_id: userId,
        user_name: userExists[0].nickname
      }
    });

  } catch (error) {
    console.error('添加停车场管理员错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 移除指定停车场的管理员
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function removeParkingLotManager(req, res) {
  try {
    const { parkingLotId, userId } = req.params;

    if (!parkingLotId || isNaN(parkingLotId)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    if (!userId || isNaN(userId)) {
      return res.status(400).json({
        success: false,
        message: '用户ID无效'
      });
    }

    // 检查管理员关系是否存在
    const existingManager = await query(
      'SELECT id FROM parking_lot_managers WHERE parking_lot_id = ? AND user_id = ?',
      [parkingLotId, userId]
    );

    if (existingManager.length === 0) {
      return res.status(404).json({
        success: false,
        message: '管理员关系不存在'
      });
    }

    // 删除管理员关系
    await query(
      'DELETE FROM parking_lot_managers WHERE parking_lot_id = ? AND user_id = ?',
      [parkingLotId, userId]
    );

    res.status(200).json({
      success: true,
      message: '移除管理员成功'
    });

  } catch (error) {
    console.error('移除停车场管理员错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取管理员列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getAdmins(req, res) {
  try {
    const { page = 1, pageSize = 10, username = '' } = req.query;

    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);

    if (pageNum < 1 || pageSizeNum < 1 || pageSizeNum > 100) {
      return res.status(400).json({
        success: false,
        message: '分页参数无效'
      });
    }

    // 构建查询条件
    let whereConditions = [];
    let queryParams = [];

    if (username.trim()) {
      whereConditions.push('username LIKE ?');
      queryParams.push(`%${username.trim()}%`);
    }

    const whereClause = whereConditions.length > 0
      ? `WHERE ${whereConditions.join(' AND ')}`
      : '';

    // 查询总数
    const countQuery = `SELECT COUNT(*) as total FROM admins ${whereClause}`;
    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const offset = (pageNum - 1) * pageSizeNum;
    const listQuery = `
      SELECT id, username, is_super_admin, is_active, created_at, updated_at
      FROM admins
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT ${pageSizeNum} OFFSET ${offset}
    `;

    const listResult = await query(listQuery, queryParams);

    res.status(200).json({
      success: true,
      data: {
        list: listResult,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    });

  } catch (error) {
    console.error('获取管理员列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 创建新管理员
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function createAdmin(req, res) {
  try {
    const { username, password, is_super_admin = 0, is_active = 1 } = req.body;

    // 基本验证
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    if (username.trim().length < 3) {
      return res.status(400).json({
        success: false,
        message: '用户名长度至少3个字符'
      });
    }

    if (password.length < 6) {
      return res.status(400).json({
        success: false,
        message: '密码长度至少6个字符'
      });
    }

    // 检查用户名是否已存在
    const existingAdmin = await query('SELECT id FROM admins WHERE username = ?', [username.trim()]);
    if (existingAdmin.length > 0) {
      return res.status(400).json({
        success: false,
        message: '用户名已存在'
      });
    }

    // 使用bcrypt加密密码
    const saltRounds = 12;
    const passwordHash = await bcrypt.hash(password, saltRounds);

    // 插入新管理员
    const insertQuery = `
      INSERT INTO admins (username, password_hash, is_super_admin, is_active)
      VALUES (?, ?, ?, ?)
    `;

    const result = await query(insertQuery, [
      username.trim(),
      passwordHash,
      is_super_admin ? 1 : 0,
      is_active ? 1 : 0
    ]);

    res.status(201).json({
      success: true,
      message: '管理员创建成功',
      data: {
        id: result.insertId,
        username: username.trim(),
        is_super_admin: is_super_admin ? 1 : 0,
        is_active: is_active ? 1 : 0
      }
    });

  } catch (error) {
    console.error('创建管理员错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 更新管理员信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateAdmin(req, res) {
  try {
    const { id } = req.params;
    const { username, password, is_super_admin, is_active } = req.body;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '管理员ID无效'
      });
    }

    // 检查管理员是否存在
    const existingAdmin = await query('SELECT id, username FROM admins WHERE id = ?', [id]);
    if (existingAdmin.length === 0) {
      return res.status(404).json({
        success: false,
        message: '管理员不存在'
      });
    }

    // 防止删除自己的超级管理员权限
    if (req.admin.id == id && req.admin.is_super_admin && is_super_admin === 0) {
      return res.status(400).json({
        success: false,
        message: '不能移除自己的超级管理员权限'
      });
    }

    // 构建更新字段
    const updateFields = [];
    const updateParams = [];

    if (username && username.trim() !== existingAdmin[0].username) {
      // 检查新用户名是否已存在
      const usernameExists = await query('SELECT id FROM admins WHERE username = ? AND id != ?', [username.trim(), id]);
      if (usernameExists.length > 0) {
        return res.status(400).json({
          success: false,
          message: '用户名已存在'
        });
      }
      updateFields.push('username = ?');
      updateParams.push(username.trim());
    }

    if (password) {
      if (password.length < 6) {
        return res.status(400).json({
          success: false,
          message: '密码长度至少6个字符'
        });
      }
      // 加密新密码
      const saltRounds = 12;
      const passwordHash = await bcrypt.hash(password, saltRounds);
      updateFields.push('password_hash = ?');
      updateParams.push(passwordHash);
    }

    if (typeof is_super_admin !== 'undefined') {
      updateFields.push('is_super_admin = ?');
      updateParams.push(is_super_admin ? 1 : 0);
    }

    if (typeof is_active !== 'undefined') {
      updateFields.push('is_active = ?');
      updateParams.push(is_active ? 1 : 0);
    }

    if (updateFields.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的字段'
      });
    }

    // 添加更新时间
    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    updateParams.push(id);

    const updateQuery = `
      UPDATE admins
      SET ${updateFields.join(', ')}
      WHERE id = ?
    `;

    await query(updateQuery, updateParams);

    res.status(200).json({
      success: true,
      message: '管理员更新成功'
    });

  } catch (error) {
    console.error('更新管理员错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 删除管理员
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function deleteAdmin(req, res) {
  try {
    const { id } = req.params;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '管理员ID无效'
      });
    }

    // 防止删除自己
    if (req.admin.id == id) {
      return res.status(400).json({
        success: false,
        message: '不能删除自己的账户'
      });
    }

    // 检查管理员是否存在
    const existingAdmin = await query('SELECT id, username, is_super_admin FROM admins WHERE id = ?', [id]);
    if (existingAdmin.length === 0) {
      return res.status(404).json({
        success: false,
        message: '管理员不存在'
      });
    }

    // 检查是否是最后一个超级管理员
    if (existingAdmin[0].is_super_admin) {
      const superAdminCount = await query('SELECT COUNT(*) as count FROM admins WHERE is_super_admin = 1');
      if (superAdminCount[0].count <= 1) {
        return res.status(400).json({
          success: false,
          message: '不能删除最后一个超级管理员'
        });
      }
    }

    // 删除管理员
    await query('DELETE FROM admins WHERE id = ?', [id]);

    res.status(200).json({
      success: true,
      message: '管理员删除成功'
    });

  } catch (error) {
    console.error('删除管理员错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取订单列表（支持复杂筛选和分页）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getOrders(req, res) {
  try {
    const {
      page = 1,
      pageSize = 10,
      order_number = '',
      license_plate = '',
      contact_phone = '',
      status = '',
      parking_lot_id = '',
      user_id = '',
      start_date = '',
      end_date = ''
    } = req.query;

    // 参数验证
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);

    if (pageNum < 1 || pageSizeNum < 1 || pageSizeNum > 100) {
      return res.status(400).json({
        success: false,
        message: '分页参数无效'
      });
    }

    // 构建查询条件
    let whereConditions = [];
    let queryParams = [];

    if (order_number.trim()) {
      whereConditions.push('o.order_number LIKE ?');
      queryParams.push(`%${order_number.trim()}%`);
    }

    if (license_plate.trim()) {
      whereConditions.push('o.license_plate LIKE ?');
      queryParams.push(`%${license_plate.trim()}%`);
    }

    if (contact_phone.trim()) {
      whereConditions.push('o.contact_phone LIKE ?');
      queryParams.push(`%${contact_phone.trim()}%`);
    }

    if (status.trim()) {
      whereConditions.push('o.status = ?');
      queryParams.push(status.trim());
    }

    if (parking_lot_id && !isNaN(parking_lot_id)) {
      whereConditions.push('o.parking_lot_id = ?');
      queryParams.push(parseInt(parking_lot_id));
    }

    if (user_id && !isNaN(user_id)) {
      whereConditions.push('o.user_id = ?');
      queryParams.push(parseInt(user_id));
    }

    if (start_date.trim()) {
      whereConditions.push('DATE(o.created_at) >= ?');
      queryParams.push(start_date.trim());
    }

    if (end_date.trim()) {
      whereConditions.push('DATE(o.created_at) <= ?');
      queryParams.push(end_date.trim());
    }

    const whereClause = whereConditions.length > 0
      ? `WHERE ${whereConditions.join(' AND ')}`
      : '';

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM orders o
      LEFT JOIN users u ON o.user_id = u.id
      LEFT JOIN parking_lots p ON o.parking_lot_id = p.id
      ${whereClause}
    `;

    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const offset = (pageNum - 1) * pageSizeNum;
    const listQuery = `
      SELECT
        o.id,
        o.order_number,
        o.user_id,
        u.nickname as user_nickname,
        u.phone_number as user_phone,
        o.parking_lot_id,
        p.name as parking_lot_name,
        o.license_plate,
        o.contact_phone,
        o.planned_start_time,
        o.planned_end_time,
        o.actual_start_time,
        o.actual_end_time,
        o.total_amount,
        o.discount_amount,
        o.final_amount,
        o.status,
        o.payment_method,
        o.transaction_id,
        o.paid_at,
        o.user_coupon_id,
        o.created_at,
        o.updated_at,
        CASE
          WHEN o.status = 'pending_payment' THEN 'pending'
          WHEN o.status = 'cancelled' THEN 'failed'
          WHEN o.paid_at IS NOT NULL THEN 'paid'
          ELSE 'pending'
        END as payment_status
      FROM orders o
      LEFT JOIN users u ON o.user_id = u.id
      LEFT JOIN parking_lots p ON o.parking_lot_id = p.id
      ${whereClause}
      ORDER BY o.created_at DESC
      LIMIT ${pageSizeNum} OFFSET ${offset}
    `;

    const listResult = await query(listQuery, queryParams);

    res.status(200).json({
      success: true,
      data: {
        list: listResult,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    });

  } catch (error) {
    console.error('获取订单列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取单个订单详细信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getOrderById(req, res) {
  try {
    const { id } = req.params;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '订单ID无效'
      });
    }

    const orderQuery = `
      SELECT
        o.*,
        u.nickname as user_nickname,
        u.phone_number as user_phone,
        u.avatar_url as user_avatar,
        p.name as parking_lot_name,
        p.address as parking_lot_address,
        p.contact_phone as parking_lot_phone,
        p.backup_phone as parking_lot_backup_phone,
        ct.name as coupon_name,
        ct.type as coupon_type,
        ct.value as coupon_value,
        uc.id as user_coupon_id,
        CASE
          WHEN o.status = 'pending_payment' THEN 'pending'
          WHEN o.status = 'cancelled' THEN 'failed'
          WHEN o.paid_at IS NOT NULL THEN 'paid'
          ELSE 'pending'
        END as payment_status,
        DATEDIFF(o.planned_end_time, o.planned_start_time) as duration_days
      FROM orders o
      LEFT JOIN users u ON o.user_id = u.id
      LEFT JOIN parking_lots p ON o.parking_lot_id = p.id
      LEFT JOIN user_coupons uc ON o.user_coupon_id = uc.id
      LEFT JOIN coupon_templates ct ON uc.template_id = ct.id
      WHERE o.id = ?
    `;

    const result = await query(orderQuery, [id]);

    if (result.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    const orderData = result[0];
    const responseData = { ...orderData };

    // 添加优惠券信息（如果有）
    if (orderData.user_coupon_id) {
      responseData.coupon_info = {
        id: orderData.user_coupon_id,
        name: orderData.coupon_name,
        type: orderData.coupon_type,
        value: orderData.coupon_value,
        discount_amount: orderData.discount_amount
      };
    }

    // 添加计费说明
    const durationDays = orderData.duration_days || 0;
    responseData.price_description = durationDays > 0
      ? `停车${durationDays}天，费用${orderData.total_amount}元`
      : `停车费用${orderData.total_amount}元`;

    res.status(200).json({
      success: true,
      data: responseData
    });

  } catch (error) {
    console.error('获取订单详情错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取用户列表（支持分页和搜索）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getUsersList(req, res) {
  try {
    const { page = 1, pageSize = 10, nickname = '', phone_number = '' } = req.query;

    // 参数验证和转换
    const pageNum = Math.max(1, parseInt(page) || 1);
    const pageSizeNum = Math.min(100, Math.max(1, parseInt(pageSize) || 10));

    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const queryParams = [];

    if (nickname && nickname.trim()) {
      whereClause += ' AND nickname LIKE ?';
      queryParams.push(`%${nickname.trim()}%`);
    }

    if (phone_number && phone_number.trim()) {
      whereClause += ' AND phone_number LIKE ?';
      queryParams.push(`%${phone_number.trim()}%`);
    }

    // 查询总数
    const countQuery = `SELECT COUNT(*) as total FROM users ${whereClause}`;
    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const offset = (pageNum - 1) * pageSizeNum;
    const listQuery = `
      SELECT
        id,
        openid,
        nickname,
        avatar_url,
        phone_number,
        created_at
      FROM users
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT ${pageSizeNum} OFFSET ${offset}
    `;

    const listResult = await query(listQuery, queryParams);

    res.status(200).json({
      success: true,
      data: {
        list: listResult,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    });

  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 创建停车场分类
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function createCategory(req, res) {
  try {
    const { name, icon_url = '', sort_order = 0 } = req.body;

    // 基本验证
    if (!name || !name.trim()) {
      return res.status(400).json({
        success: false,
        message: '分类名称不能为空'
      });
    }

    // 检查分类名称是否已存在
    const existingCategory = await query('SELECT id FROM parking_lot_categories WHERE name = ?', [name.trim()]);
    if (existingCategory.length > 0) {
      return res.status(400).json({
        success: false,
        message: '分类名称已存在'
      });
    }

    // 插入新分类
    const insertQuery = `
      INSERT INTO parking_lot_categories (name, icon_url, sort_order)
      VALUES (?, ?, ?)
    `;

    const result = await query(insertQuery, [
      name.trim(),
      icon_url || '',
      parseInt(sort_order) || 0
    ]);

    res.status(201).json({
      success: true,
      message: '分类创建成功',
      data: {
        id: result.insertId,
        name: name.trim(),
        icon_url: icon_url || '',
        sort_order: parseInt(sort_order) || 0
      }
    });

  } catch (error) {
    console.error('创建分类错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 更新停车场分类
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateCategory(req, res) {
  try {
    const { id } = req.params;
    const { name, icon_url, sort_order } = req.body;

    // 验证ID
    if (!id || isNaN(parseInt(id))) {
      return res.status(400).json({
        success: false,
        message: '无效的分类ID'
      });
    }

    // 检查分类是否存在
    const existingCategory = await query('SELECT * FROM parking_lot_categories WHERE id = ?', [id]);
    if (existingCategory.length === 0) {
      return res.status(404).json({
        success: false,
        message: '分类不存在'
      });
    }

    // 如果要更新名称，检查是否与其他分类重名
    if (name && name.trim() && name.trim() !== existingCategory[0].name) {
      const duplicateCategory = await query('SELECT id FROM parking_lot_categories WHERE name = ? AND id != ?', [name.trim(), id]);
      if (duplicateCategory.length > 0) {
        return res.status(400).json({
          success: false,
          message: '分类名称已存在'
        });
      }
    }

    // 构建更新字段
    const updateFields = [];
    const updateParams = [];

    if (name && name.trim()) {
      updateFields.push('name = ?');
      updateParams.push(name.trim());
    }

    if (icon_url !== undefined) {
      updateFields.push('icon_url = ?');
      updateParams.push(icon_url || '');
    }

    if (sort_order !== undefined) {
      updateFields.push('sort_order = ?');
      updateParams.push(parseInt(sort_order) || 0);
    }

    if (updateFields.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的字段'
      });
    }

    updateParams.push(id);

    // 执行更新
    const updateQuery = `UPDATE parking_lot_categories SET ${updateFields.join(', ')} WHERE id = ?`;
    await query(updateQuery, updateParams);

    res.status(200).json({
      success: true,
      message: '分类更新成功'
    });

  } catch (error) {
    console.error('更新分类错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 删除停车场分类
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function deleteCategory(req, res) {
  try {
    const { id } = req.params;

    // 验证ID
    if (!id || isNaN(parseInt(id))) {
      return res.status(400).json({
        success: false,
        message: '无效的分类ID'
      });
    }

    // 检查分类是否存在
    const existingCategory = await query('SELECT * FROM parking_lot_categories WHERE id = ?', [id]);
    if (existingCategory.length === 0) {
      return res.status(404).json({
        success: false,
        message: '分类不存在'
      });
    }

    // 检查是否有停车场使用此分类
    const parkingLotsUsingCategory = await query('SELECT COUNT(*) as count FROM parking_lots WHERE category_id = ?', [id]);
    if (parkingLotsUsingCategory[0].count > 0) {
      return res.status(400).json({
        success: false,
        message: '该分类下还有停车场，无法删除'
      });
    }

    // 删除分类
    await query('DELETE FROM parking_lot_categories WHERE id = ?', [id]);

    res.status(200).json({
      success: true,
      message: '分类删除成功'
    });

  } catch (error) {
    console.error('删除分类错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取系统配置
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getSystemConfig(req, res) {
  try {
    const { config_key } = req.query;

    // 验证参数
    if (!config_key || !config_key.trim()) {
      return res.status(400).json({
        success: false,
        message: '配置键不能为空'
      });
    }

    // 查询配置
    const configQuery = 'SELECT config_value, description FROM system_configs WHERE config_key = ?';
    const result = await query(configQuery, [config_key.trim()]);

    if (result.length === 0) {
      return res.status(404).json({
        success: false,
        message: '配置项不存在'
      });
    }

    res.status(200).json({
      success: true,
      data: {
        config_key: config_key.trim(),
        config_value: result[0].config_value,
        description: result[0].description
      }
    });

  } catch (error) {
    console.error('获取系统配置错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 更新系统配置
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateSystemConfig(req, res) {
  try {
    const { config_key, config_value, description = '' } = req.body;

    // 验证参数
    if (!config_key || !config_key.trim()) {
      return res.status(400).json({
        success: false,
        message: '配置键不能为空'
      });
    }

    if (config_value === undefined || config_value === null) {
      return res.status(400).json({
        success: false,
        message: '配置值不能为空'
      });
    }

    // 使用 INSERT ... ON DUPLICATE KEY UPDATE 语句
    const upsertQuery = `
      INSERT INTO system_configs (config_key, config_value, description)
      VALUES (?, ?, ?)
      ON DUPLICATE KEY UPDATE
        config_value = VALUES(config_value),
        description = VALUES(description)
    `;

    await query(upsertQuery, [
      config_key.trim(),
      typeof config_value === 'string' ? config_value : JSON.stringify(config_value),
      description || ''
    ]);

    res.status(200).json({
      success: true,
      message: '配置更新成功'
    });

  } catch (error) {
    console.error('更新系统配置错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 测试短信发送
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function testSms(req, res) {
  try {
    const { phone } = req.body;

    // 参数验证
    if (!phone) {
      return res.status(400).json({
        success: false,
        message: '手机号码不能为空'
      });
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      return res.status(400).json({
        success: false,
        message: '手机号格式无效'
      });
    }

    // 调用短信服务测试功能
    const { testSmsConfig } = require('../services/SmsService');
    const result = await testSmsConfig(phone);

    if (result.success) {
      res.json({
        success: true,
        message: '测试短信发送成功',
        data: result.data
      });
    } else {
      res.status(400).json({
        success: false,
        message: result.message || '测试短信发送失败'
      });
    }

  } catch (error) {
    console.error('测试短信发送错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// ==================== 优惠券模板管理 ====================

/**
 * 获取优惠券模板列表（支持分页和搜索）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getCouponTemplates(req, res) {
  try {
    const { page = 1, pageSize = 10, name = '' } = req.query;

    // 参数验证
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);

    if (pageNum < 1 || pageSizeNum < 1 || pageSizeNum > 100) {
      return res.status(400).json({
        success: false,
        message: '分页参数无效'
      });
    }

    // 构建查询条件
    let whereConditions = [];
    let queryParams = [];

    if (name.trim()) {
      whereConditions.push('name LIKE ?');
      queryParams.push(`%${name.trim()}%`);
    }

    const whereClause = whereConditions.length > 0
      ? `WHERE ${whereConditions.join(' AND ')}`
      : '';

    // 查询总数
    const countQuery = `SELECT COUNT(*) as total FROM coupon_templates ${whereClause}`;
    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const offset = (pageNum - 1) * pageSizeNum;
    const listQuery = `
      SELECT
        id,
        name,
        type,
        value,
        min_spend,
        validity_type,
        valid_days,
        valid_start_date,
        valid_end_date,
        total_quantity,
        issued_quantity,
        is_active,
        created_at,
        updated_at
      FROM coupon_templates
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT ${pageSizeNum} OFFSET ${offset}
    `;

    const listResult = await query(listQuery, queryParams);

    res.status(200).json({
      success: true,
      data: {
        list: listResult,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    });

  } catch (error) {
    console.error('获取优惠券模板列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 创建优惠券模板
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function createCouponTemplate(req, res) {
  try {
    const {
      name,
      type,
      value,
      min_spend = 0,
      validity_type,
      valid_days,
      valid_start_date,
      valid_end_date,
      total_quantity = -1,
      is_active = 1
    } = req.body;

    // 基本验证
    if (!name || !type || !value || !validity_type) {
      return res.status(400).json({
        success: false,
        message: '优惠券名称、类型、面值和有效期类型不能为空'
      });
    }

    if (name.trim().length < 2) {
      return res.status(400).json({
        success: false,
        message: '优惠券名称长度至少2个字符'
      });
    }

    // 验证类型
    if (!['fixed', 'discount'].includes(type)) {
      return res.status(400).json({
        success: false,
        message: '优惠券类型无效'
      });
    }

    // 验证面值
    const valueNum = parseFloat(value);
    if (isNaN(valueNum) || valueNum <= 0) {
      return res.status(400).json({
        success: false,
        message: '面值必须为正数'
      });
    }

    // 折扣券面值不能超过10
    if (type === 'discount' && valueNum > 10) {
      return res.status(400).json({
        success: false,
        message: '折扣券面值不能超过10'
      });
    }

    // 验证最低消费
    const minSpendNum = parseFloat(min_spend) || 0;
    if (minSpendNum < 0) {
      return res.status(400).json({
        success: false,
        message: '最低消费不能为负数'
      });
    }

    // 验证有效期类型
    if (!['fixed_days', 'date_range'].includes(validity_type)) {
      return res.status(400).json({
        success: false,
        message: '有效期类型无效'
      });
    }

    // 根据有效期类型验证相关字段
    let validDaysValue = null;
    let validStartDateValue = null;
    let validEndDateValue = null;

    if (validity_type === 'fixed_days') {
      const validDaysNum = parseInt(valid_days);
      if (isNaN(validDaysNum) || validDaysNum <= 0) {
        return res.status(400).json({
          success: false,
          message: '有效天数必须为正整数'
        });
      }
      validDaysValue = validDaysNum;
    } else if (validity_type === 'date_range') {
      if (!valid_start_date || !valid_end_date) {
        return res.status(400).json({
          success: false,
          message: '日期范围类型必须提供开始和结束日期'
        });
      }

      const startDate = new Date(valid_start_date);
      const endDate = new Date(valid_end_date);

      if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
        return res.status(400).json({
          success: false,
          message: '日期格式无效'
        });
      }

      if (startDate >= endDate) {
        return res.status(400).json({
          success: false,
          message: '结束日期必须晚于开始日期'
        });
      }

      validStartDateValue = valid_start_date;
      validEndDateValue = valid_end_date;
    }

    // 验证发行总量
    const totalQuantityNum = parseInt(total_quantity);
    if (isNaN(totalQuantityNum) || (totalQuantityNum !== -1 && totalQuantityNum <= 0)) {
      return res.status(400).json({
        success: false,
        message: '发行总量必须为正整数或-1（不限量）'
      });
    }

    // 插入优惠券模板
    const insertQuery = `
      INSERT INTO coupon_templates (
        name, type, value, min_spend, validity_type,
        valid_days, valid_start_date, valid_end_date,
        total_quantity, is_active
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;

    const insertParams = [
      name.trim(),
      type,
      valueNum,
      minSpendNum,
      validity_type,
      validDaysValue,
      validStartDateValue,
      validEndDateValue,
      totalQuantityNum,
      is_active ? 1 : 0
    ];

    const result = await query(insertQuery, insertParams);

    res.status(201).json({
      success: true,
      message: '优惠券模板创建成功',
      data: {
        id: result.insertId
      }
    });

  } catch (error) {
    console.error('创建优惠券模板错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 更新优惠券模板
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateCouponTemplate(req, res) {
  try {
    const { id } = req.params;
    const {
      name,
      type,
      value,
      min_spend = 0,
      validity_type,
      valid_days,
      valid_start_date,
      valid_end_date,
      total_quantity = -1,
      is_active = 1
    } = req.body;

    // 验证ID
    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '优惠券模板ID无效'
      });
    }

    // 检查模板是否存在
    const existingTemplate = await query('SELECT id FROM coupon_templates WHERE id = ?', [id]);
    if (existingTemplate.length === 0) {
      return res.status(404).json({
        success: false,
        message: '优惠券模板不存在'
      });
    }

    // 基本验证（与创建时相同的验证逻辑）
    if (!name || !type || !value || !validity_type) {
      return res.status(400).json({
        success: false,
        message: '优惠券名称、类型、面值和有效期类型不能为空'
      });
    }

    if (name.trim().length < 2) {
      return res.status(400).json({
        success: false,
        message: '优惠券名称长度至少2个字符'
      });
    }

    // 验证类型
    if (!['fixed', 'discount'].includes(type)) {
      return res.status(400).json({
        success: false,
        message: '优惠券类型无效'
      });
    }

    // 验证面值
    const valueNum = parseFloat(value);
    if (isNaN(valueNum) || valueNum <= 0) {
      return res.status(400).json({
        success: false,
        message: '面值必须为正数'
      });
    }

    // 折扣券面值不能超过10
    if (type === 'discount' && valueNum > 10) {
      return res.status(400).json({
        success: false,
        message: '折扣券面值不能超过10'
      });
    }

    // 验证最低消费
    const minSpendNum = parseFloat(min_spend) || 0;
    if (minSpendNum < 0) {
      return res.status(400).json({
        success: false,
        message: '最低消费不能为负数'
      });
    }

    // 验证有效期类型
    if (!['fixed_days', 'date_range'].includes(validity_type)) {
      return res.status(400).json({
        success: false,
        message: '有效期类型无效'
      });
    }

    // 根据有效期类型验证相关字段
    let validDaysValue = null;
    let validStartDateValue = null;
    let validEndDateValue = null;

    if (validity_type === 'fixed_days') {
      const validDaysNum = parseInt(valid_days);
      if (isNaN(validDaysNum) || validDaysNum <= 0) {
        return res.status(400).json({
          success: false,
          message: '有效天数必须为正整数'
        });
      }
      validDaysValue = validDaysNum;
    } else if (validity_type === 'date_range') {
      if (!valid_start_date || !valid_end_date) {
        return res.status(400).json({
          success: false,
          message: '日期范围类型必须提供开始和结束日期'
        });
      }

      const startDate = new Date(valid_start_date);
      const endDate = new Date(valid_end_date);

      if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
        return res.status(400).json({
          success: false,
          message: '日期格式无效'
        });
      }

      if (startDate >= endDate) {
        return res.status(400).json({
          success: false,
          message: '结束日期必须晚于开始日期'
        });
      }

      validStartDateValue = valid_start_date;
      validEndDateValue = valid_end_date;
    }

    // 验证发行总量
    const totalQuantityNum = parseInt(total_quantity);
    if (isNaN(totalQuantityNum) || (totalQuantityNum !== -1 && totalQuantityNum <= 0)) {
      return res.status(400).json({
        success: false,
        message: '发行总量必须为正整数或-1（不限量）'
      });
    }

    // 更新优惠券模板
    const updateQuery = `
      UPDATE coupon_templates SET
        name = ?,
        type = ?,
        value = ?,
        min_spend = ?,
        validity_type = ?,
        valid_days = ?,
        valid_start_date = ?,
        valid_end_date = ?,
        total_quantity = ?,
        is_active = ?,
        updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;

    const updateParams = [
      name.trim(),
      type,
      valueNum,
      minSpendNum,
      validity_type,
      validDaysValue,
      validStartDateValue,
      validEndDateValue,
      totalQuantityNum,
      is_active ? 1 : 0,
      id
    ];

    await query(updateQuery, updateParams);

    res.status(200).json({
      success: true,
      message: '优惠券模板更新成功'
    });

  } catch (error) {
    console.error('更新优惠券模板错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 删除优惠券模板
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function deleteCouponTemplate(req, res) {
  try {
    const { id } = req.params;

    // 验证ID
    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '优惠券模板ID无效'
      });
    }

    // 检查模板是否存在
    const existingTemplate = await query('SELECT id FROM coupon_templates WHERE id = ?', [id]);
    if (existingTemplate.length === 0) {
      return res.status(404).json({
        success: false,
        message: '优惠券模板不存在'
      });
    }

    // 删除优惠券模板（数据库外键约束会自动处理关联的用户优惠券）
    await query('DELETE FROM coupon_templates WHERE id = ?', [id]);

    res.status(200).json({
      success: true,
      message: '优惠券模板删除成功'
    });

  } catch (error) {
    console.error('删除优惠券模板错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取Dashboard统计数据
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getDashboardStats(req, res) {
  try {
    // 并行执行多个查询以提高性能
    const [
      todayRevenueResult,
      totalRevenueResult,
      todayNewUsersResult,
      totalUsersResult,
      pendingOrdersResult,
      totalParkingLotsResult
    ] = await Promise.all([
      // 今日收入
      query(`
        SELECT COALESCE(SUM(final_amount), 0) as revenue
        FROM orders
        WHERE DATE(paid_at) = CURDATE() AND status = 'completed'
      `),

      // 总收入
      query(`
        SELECT COALESCE(SUM(final_amount), 0) as revenue
        FROM orders
        WHERE status = 'completed'
      `),

      // 今日新增用户数
      query(`
        SELECT COUNT(*) as count
        FROM users
        WHERE DATE(created_at) = CURDATE()
      `),

      // 总用户数
      query(`
        SELECT COUNT(*) as count
        FROM users
      `),

      // 待处理订单数
      query(`
        SELECT COUNT(*) as count
        FROM orders
        WHERE status = 'in_progress'
      `),

      // 停车场总数
      query(`
        SELECT COUNT(*) as count
        FROM parking_lots
      `)
    ]);

    // 构建返回数据
    const dashboardStats = {
      todayRevenue: parseFloat(todayRevenueResult[0].revenue || 0),
      totalRevenue: parseFloat(totalRevenueResult[0].revenue || 0),
      todayNewUsers: parseInt(todayNewUsersResult[0].count || 0),
      totalUsers: parseInt(totalUsersResult[0].count || 0),
      pendingOrders: parseInt(pendingOrdersResult[0].count || 0),
      totalParkingLots: parseInt(totalParkingLotsResult[0].count || 0)
    };

    res.status(200).json({
      success: true,
      data: dashboardStats
    });

  } catch (error) {
    console.error('获取Dashboard统计数据错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 向用户发放优惠券
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function issueCouponToUser(req, res) {
  const { beginTransaction, commitTransaction, rollbackTransaction } = require('../config/db');
  const connection = await beginTransaction();

  try {
    const { template_id, user_id } = req.body;

    // 参数验证
    if (!template_id || !user_id) {
      return res.status(400).json({
        success: false,
        message: '模板ID和用户ID不能为空'
      });
    }

    // 事务已在beginTransaction()中开始

    // 查询优惠券模板信息
    const templateQuery = `
      SELECT id, name, type, value, min_spend, validity_type, valid_days,
             valid_start_date, valid_end_date, total_quantity, issued_quantity, is_active
      FROM coupon_templates
      WHERE id = ? AND is_active = 1
    `;
    const [templateResult] = await connection.execute(templateQuery, [template_id]);

    if (templateResult.length === 0) {
      await connection.rollback();
      return res.status(404).json({
        success: false,
        message: '优惠券模板不存在或已禁用'
      });
    }

    const template = templateResult[0];

    // 检查发放数量限制
    if (template.total_quantity > 0 && template.issued_quantity >= template.total_quantity) {
      await connection.rollback();
      return res.status(400).json({
        success: false,
        message: '优惠券发放数量已达上限'
      });
    }

    // 验证用户是否存在
    const userQuery = `SELECT id, nickname FROM users WHERE id = ?`;
    const [userResult] = await connection.execute(userQuery, [user_id]);

    if (userResult.length === 0) {
      await connection.rollback();
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 计算优惠券有效期
    let expiryDate;
    if (template.validity_type === 'fixed_days') {
      // 固定天数：从今天开始计算
      const today = new Date();
      expiryDate = new Date(today.getTime() + template.valid_days * 24 * 60 * 60 * 1000);
    } else {
      // 日期范围：使用模板的结束日期
      expiryDate = new Date(template.valid_end_date);
    }

    // 检查用户是否已经拥有相同模板的未使用优惠券
    const existingCouponQuery = `
      SELECT id FROM user_coupons
      WHERE user_id = ? AND template_id = ? AND status = 'unused' AND expiry_date > NOW()
    `;
    const [existingResult] = await connection.execute(existingCouponQuery, [user_id, template_id]);

    if (existingResult.length > 0) {
      await connection.rollback();
      return res.status(400).json({
        success: false,
        message: '用户已拥有相同类型的未使用优惠券'
      });
    }

    // 插入用户优惠券记录
    const insertCouponQuery = `
      INSERT INTO user_coupons (user_id, template_id, status, expiry_date, issue_date)
      VALUES (?, ?, 'unused', ?, NOW())
    `;
    const [insertResult] = await connection.execute(insertCouponQuery, [user_id, template_id, expiryDate]);

    // 更新模板的已发放数量
    const updateTemplateQuery = `
      UPDATE coupon_templates
      SET issued_quantity = issued_quantity + 1, updated_at = NOW()
      WHERE id = ?
    `;
    await connection.execute(updateTemplateQuery, [template_id]);

    // 提交事务
    await commitTransaction(connection);

    res.status(201).json({
      success: true,
      message: '优惠券发放成功',
      data: {
        coupon_id: insertResult.insertId,
        user_nickname: userResult[0].nickname,
        template_name: template.name,
        expiry_date: expiryDate
      }
    });

  } catch (error) {
    // 回滚事务
    await rollbackTransaction(connection);
    console.error('发放优惠券错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  } finally {
    // 连接已在commitTransaction或rollbackTransaction中释放
  }
}

/**
 * 更新停车场管理员邮箱
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateParkingLotManagerEmail(req, res) {
  try {
    console.log('🔧 updateParkingLotManagerEmail API 被调用');
    console.log('📥 请求参数:', { params: req.params, body: req.body });

    const { parkingLotId, userId } = req.params;
    const { email } = req.body;

    // 参数验证
    if (!parkingLotId || isNaN(parkingLotId)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    if (!userId || isNaN(userId)) {
      return res.status(400).json({
        success: false,
        message: '用户ID无效'
      });
    }

    // 验证邮箱格式（如果提供了邮箱）
    if (email && email.trim()) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(email.trim())) {
        return res.status(400).json({
          success: false,
          message: '邮箱格式无效'
        });
      }
    }

    // 检查停车场是否存在
    const parkingLotExists = await query('SELECT id FROM parking_lots WHERE id = ?', [parkingLotId]);
    if (parkingLotExists.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    // 检查用户是否是该停车场的管理员
    const managerExists = await query(
      'SELECT id FROM parking_lot_managers WHERE parking_lot_id = ? AND user_id = ?',
      [parkingLotId, userId]
    );

    if (managerExists.length === 0) {
      return res.status(404).json({
        success: false,
        message: '该用户不是此停车场的管理员'
      });
    }

    // 更新用户邮箱
    const updateResult = await query(
      'UPDATE users SET email = ? WHERE id = ?',
      [email ? email.trim() : '', userId]
    );

    if (updateResult.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 获取更新后的管理员信息
    const updatedManager = await query(
      `SELECT u.id, u.nickname, u.phone_number, u.email, u.avatar_url, u.created_at, plm.id as manager_relation_id
       FROM parking_lot_managers plm
       JOIN users u ON plm.user_id = u.id
       WHERE plm.parking_lot_id = ? AND u.id = ?`,
      [parkingLotId, userId]
    );

    res.status(200).json({
      success: true,
      message: '邮箱更新成功',
      data: updatedManager[0]
    });

  } catch (error) {
    console.error('更新管理员邮箱错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 测试邮件发送
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function testEmail(req, res) {
  try {
    const { email } = req.body;

    // 参数验证
    if (!email) {
      return res.status(400).json({
        success: false,
        message: '邮箱地址不能为空'
      });
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({
        success: false,
        message: '邮箱格式无效'
      });
    }

    // 调用邮件服务测试功能
    const { testEmailSending } = require('../services/EmailService');
    const result = await testEmailSending(email);

    if (result.success) {
      res.json({
        success: true,
        message: '测试邮件发送成功',
        data: result.data
      });
    } else {
      res.status(400).json({
        success: false,
        message: result.message || '测试邮件发送失败'
      });
    }

  } catch (error) {
    console.error('测试邮件发送错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

module.exports = {
  login,
  getCurrentAdmin,
  getParkingLots,
  getParkingLotById,
  createParkingLot,
  updateParkingLot,
  deleteParkingLot,
  getParkingLotReviews,
  addParkingLotReview,
  updateReviewStatus,
  replyToReview,
  getParkingLotCategories,
  searchUsers,
  getParkingLotManagers,
  addParkingLotManager,
  removeParkingLotManager,
  updateParkingLotManagerEmail,
  getAdmins,
  createAdmin,
  updateAdmin,
  deleteAdmin,
  getOrders,
  getOrderById,
  getUsersList,
  createCategory,
  updateCategory,
  deleteCategory,
  getSystemConfig,
  updateSystemConfig,
  testSms,
  testEmail,
  getCouponTemplates,
  createCouponTemplate,
  updateCouponTemplate,
  deleteCouponTemplate,
  getDashboardStats,
  issueCouponToUser
};
